//
//  LoginViewController.m
//  Kaagad Peso
//
//  Created by ZhengChengFeng on 2024/10/15.
//

#import "LoginViewController.h"
#import "AgreementView.h"

@interface LoginViewController ()<UITextFieldDelegate,CLLocationManagerDelegate>

@property (nonatomic) UIView *backView;
@property (nonatomic) UIView *whiteView,*view1;

@property (nonatomic) UITextFieldHelper *phoneFiled,*captureFiled;
@property (nonatomic) UIButton *captureBtn,*loginBtn;
@property (nonatomic) NSTimer *timer;
@property (nonatomic) BOOL agree;
@property (nonatomic) BOOL isNetworkError;




@property (nonatomic) NSString *startTimeStr,*endTimeStr;

@end

#define kDefaultTime    60

static int timeCount = kDefaultTime;

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [DataCategoryUpload uploadDataIDFA:YES];
    
    if ([[CurrentUser mine] isYNLanguage]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kRecordLoginStartTime];
        self.startTimeStr = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
        [[NSUserDefaults standardUserDefaults] setValue:self.startTimeStr forKey:kRecordLoginStartTime];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kShadowViewColor;
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - (82+428), kScreenWidth, 82+428)];
    [self.view addSubview:self.backView];
    self.backView.backgroundColor = [UIColor clearColor];
    
    
    self.whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 82, kScreenWidth, self.backView.height - 82)];
    self.whiteView.backgroundColor = [UIColor whiteColor];
    [self.backView addSubview:self.whiteView];
    self.whiteView.layer.mask = [NSString UIBezierPathWithRect:self.whiteView.bounds withCorners:UIRectCornerTopLeft|UIRectCornerTopRight withRadiu:CGSizeMake(10, 10)];
    
    [self initUI];
    
    UIImage *img1 = [UIImage imageNamed:@"icon_login1"];
    if ([CurrentUser mine].isYNLanguage) {
        img1 = [UIImage imageNamed:@"icon_login1-yn"];
    }
    UIImageView *icon1 = [[UIImageView alloc] init];
    [self.backView addSubview:icon1];
    icon1.image = img1;
    icon1.frame = CGRectMake((kScreenWidth - 182)/2, 0, 182, 164);
    
    
}

- (void)clickCancel{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)initUI{
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.whiteView.width - 40, 0, 40, 40)];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_cancel"] forState:UIControlStateSelected];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_cancel"] forState:UIControlStateNormal];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_cancel"] forState:UIControlStateHighlighted];
    [cancelBtn addTarget:self action:@selector(clickCancel) forControlEvents:UIControlEventTouchUpInside];
    [self.whiteView addSubview:cancelBtn];
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(30, 96, kScreenWidth - 60, 83)];
    view1.backgroundColor = [UIColor colorWithHexString:@"#F7F7F7"];
    [self.whiteView addSubview:view1];
    view1.layer.cornerRadius = 14;
    view1.layer.masksToBounds = YES;
    view1.layer.borderColor = [UIColor colorWithHexString:@"#EFEFEF"].CGColor;
    view1.layer.borderWidth = 1;
    self.view1 = view1;
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(30, view1.bottom + 26, kScreenWidth - 60, 83)];
    view2.backgroundColor = [UIColor colorWithHexString:@"#F7F7F7"];
    [self.whiteView addSubview:view2];
    view2.layer.cornerRadius = 14;
    view2.layer.masksToBounds = YES;
    view2.layer.borderColor = [UIColor colorWithHexString:@"#EFEFEF"].CGColor;
    view2.layer.borderWidth = 1;
    
    UILabel *lab1 = [UILabel createLabel:[UIFont fontWithName:kFuturaBT size:14] color:kBlackColor];
    lab1.text = ASLocalizedString(@"Phone");
    lab1.frame = CGRectMake(15, 15, 150, 15);
    [view1 addSubview:lab1];
    
    UIImage *img1 = [UIImage imageNamed:@"icon_logTip"];
    if ([CurrentUser mine].isYNLanguage) {
        img1 = [UIImage imageNamed:@"icon_logTip_yn"];
    }
    UIImageView *ic1 = [[UIImageView alloc] initWithFrame:CGRectMake(lab1.left, lab1.bottom + 28, 0, 0)];
//    ic1.image = img1;
    [view1 addSubview:ic1];
    
    UILabel *lab11 = [UILabel createLabel:[UIFont fontWithName:kFuturaBT size:14] color:kBlackColor];
    lab11.text = @"+ 91";
    if ([CurrentUser mine].isYNLanguage) {
        lab11.text = @"+ 62";
    }
    lab11.frame = CGRectMake(ic1.right, 0, 35, 14);
    [view1 addSubview:lab11];
    lab11.centerY = ic1.centerY;
    
    UIView *lineV = [[UIView alloc] init];
    lineV.backgroundColor = [UIColor colorWithHexString:@"#6C6C6C"];
    lineV.frame = CGRectMake(lab11.right + 6, 0, 1, 12);
    lineV.centerY = ic1.centerY;
    [view1 addSubview:lineV];
    
    self.phoneFiled = [[UITextFieldHelper alloc] init];
    self.phoneFiled.frame = CGRectMake(lineV.right + 6, 0, view1.width - lineV.right - 6 - 15, 16);
    [view1 addSubview:self.phoneFiled];
    self.phoneFiled.delegate = self;
    self.phoneFiled.font = [UIFont fontWithName:kGeometricBT size:14];
    self.phoneFiled.placeholder = ASLocalizedString(@"PhonePlaceholder");
    self.phoneFiled.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneFiled.textColor = kBlackColor;
    self.phoneFiled.limitedCount = 16;
    self.phoneFiled.centerY = ic1.centerY;
    
    NSMutableAttributedString *placeholderString1 = [[NSMutableAttributedString alloc] initWithString:self.phoneFiled.placeholder attributes:@{NSFontAttributeName : [UIFont fontWithName:kFutura size:14],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#6C6C6C"]}];
    self.phoneFiled.attributedPlaceholder = placeholderString1;
    
    
    UILabel *lab2 = [UILabel createLabel:[UIFont fontWithName:kFuturaBT size:14] color:kBlackColor];
    lab2.text = ASLocalizedString(@"Capture");
    lab2.frame = CGRectMake(15, 15, 150, 15);
    [view2 addSubview:lab2];
    
    self.captureFiled = [[UITextFieldHelper alloc]init];
    self.captureFiled.frame = CGRectMake(lab2.left, lab2.bottom + 20, view2.width - lab2.left - 15 - 100, 16);
    self.captureFiled.limitedCount = 6;
    self.captureFiled.delegate = self;
    self.captureFiled.font = [UIFont fontWithName:kGeometricBT size:14];
    self.captureFiled.placeholder = ASLocalizedString(@"CapturePlaceholder");
    self.captureFiled.keyboardType = UIKeyboardTypeNumberPad;
    self.captureFiled.textColor = kBlackColor;
    [view2 addSubview:self.captureFiled];
    
    NSMutableAttributedString *placeholderCapString2 = [[NSMutableAttributedString alloc] initWithString:self.captureFiled.placeholder attributes:@{NSFontAttributeName : [UIFont fontWithName:kFutura size:14],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#6C6C6C"]}];
    self.captureFiled.attributedPlaceholder = placeholderCapString2;
    
    
    UIButton *getCaptchaButton = [[UIButton alloc]initWithFrame:CGRectMake(view2.width - 15 - 100, 0, 100, 16)];
    self.captureBtn = getCaptchaButton;
    [view2 addSubview:self.captureBtn];
    [getCaptchaButton setTitle:ASLocalizedString(@"Get") forState:UIControlStateNormal];
    [getCaptchaButton setTitleColor:kButtonDefaultColor forState:UIControlStateNormal];
    getCaptchaButton.titleLabel.font = [UIFont fontWithName:kFutura size:14];
    [getCaptchaButton addTarget:self action:@selector(getCaptchaCode) forControlEvents:UIControlEventTouchUpInside];
    getCaptchaButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    getCaptchaButton.centerY = self.captureFiled.centerY;
    
    self.loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(view1.left, view2.bottom + 24, kScreenWidth - view1.left*2, 48)];
    [self.loginBtn setTitle:ASLocalizedString(@"LoginBtn") forState:UIControlStateNormal];
    [self.loginBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateNormal];
    self.loginBtn.titleLabel.font = [UIFont fontWithName:kGeometricBT size:15];
    [self.loginBtn addTarget:self action:@selector(clickLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.whiteView addSubview:self.loginBtn];
    [self.loginBtn setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
    
    self.loginBtn.backgroundColor = kButtonDefaultColor;
    self.loginBtn.layer.cornerRadius = 48/2;
    self.loginBtn.layer.masksToBounds = YES;
    
    [self.loginBtn setImgRightTitltLeft:18];
    
    
    NSString *str1 = ASLocalizedString(@"Privacy1");
    NSString *str2 = ASLocalizedString(@"Privacy2");
    
    NSString *textStr = [NSString stringWithFormat:@"%@%@",str1,str2];
    CGRect rec = [textStr boundingRectWithSize:CGSizeMake(kScreenWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:kFutura size:12]} context:nil];
    
    
    AgreementView *agreeView = [[AgreementView alloc]initWithTitle:str1 withTitleColor:[UIColor colorWithHexString:@"#6C6C6C"] protocol:str2 withProtocolColor:kButtonDefaultColor fontSize:12 target:self withSel:YES withAgreeImg:@"icon_agree" withUnagreeImg:@"icon_unagree"];
    agreeView.frame = CGRectMake((kScreenWidth - rec.size.width - 10)/2,DimensionBaseIphone6(10) + self.loginBtn.bottom, rec.size.width + 10, DimensionBaseIphone6(16));
    [self.whiteView addSubview:agreeView];
    
    self.agree = YES;
    
    
    if (!PMStringIsEmpty([[NSUserDefaults standardUserDefaults] valueForKey:kUserTelPhone])) {
        self.phoneFiled.text = esString([[NSUserDefaults standardUserDefaults] valueForKey:kUserTelPhone]);
    }
    
    if (self.phoneFiled.text.length >= 10) {
        self.view1.backgroundColor = [UIColor colorWithHexString:@"#75FA8D"];
        self.view1.layer.borderColor = kButtonDefaultColor.CGColor;
        self.view1.layer.borderWidth = 1;
    } else {
        self.view1.backgroundColor = [UIColor colorWithHexString:@"#F7F7F7"];
        self.view1.layer.borderColor = [UIColor colorWithHexString:@"#EFEFEF"].CGColor;
        self.view1.layer.borderWidth = 1;
    }
    
}

- (void)agreeViewWillShowProtocol{
    [self.view endEditing:YES];
    [self clickCancel];
    [[DKCore sharedDKCore] jumpToControllerWithUrlString:[NSString stringWithFormat:@"%@",kAgreementUrl]];
}

- (void)agreeViewWillAgreeProtocol:(BOOL)agree{
    self.agree = agree;
}

- (void)textFieldDidChangeSelection:(UITextField *)textField{
    if (textField == self.captureFiled) {
        if (self.captureFiled.text.length == 6) {
            [self clickLogin];
        }
    }
    
    if (textField == self.phoneFiled) {
        if (self.phoneFiled.text.length >= 10) {
            self.view1.backgroundColor = [UIColor colorWithHexString:@"#75FA8D"];
            self.view1.layer.borderColor = kButtonDefaultColor.CGColor;
            self.view1.layer.borderWidth = 1;
        } else {
            self.view1.backgroundColor = [UIColor colorWithHexString:@"#F7F7F7"];
            self.view1.layer.borderColor = [UIColor colorWithHexString:@"#EFEFEF"].CGColor;
            self.view1.layer.borderWidth = 1;
        }
    }
}


#pragma mark textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


#pragma mark login
- (void)clickLogin{
    
    [self.view endEditing:YES];
    
    if (!self.agree) {
        [BoxLoadingHelper showBoxWithMessage:ASLocalizedString(@"PrivacyTips")];
        return;
    }
    
    if (PMStringIsEmpty(self.phoneFiled.text)) {
        [BoxLoadingHelper showBoxWithMessage:ASLocalizedString(@"PhoneTips")];
        return;
    }
    
    if (PMStringIsEmpty(self.captureFiled.text)) {
        [BoxLoadingHelper showBoxWithMessage:ASLocalizedString(@"CaptureTips")];
        return;
    }
    
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"atonement":esString(self.phoneFiled.text),
        @"indirectly":esString(self.captureFiled.text),
        @"collected":@"collectedLogin",
        @"guilty":@"guiltyLogin"
    }.mutableCopy;
    
    [HttpNetHelper postNetworkHelperForPath:kLoginUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        
        NSDictionary *dataDic = responseDic[@"clip"];
        
        [CurrentUser loginSuccess:esString(dataDic[@"emanation"])];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationLoginSucess object:nil];
        
        
        if (self.navigationController.finishBlock) {
            self.navigationController.finishBlock();
        }
        
        [self clickCancel];
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserTelPhone];
        [[NSUserDefaults standardUserDefaults] setValue:esString(self.phoneFiled.text) forKey:kUserTelPhone];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kRecordLoginEndTime];
        self.endTimeStr = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
        [[NSUserDefaults standardUserDefaults] setValue:self.endTimeStr forKey:kRecordLoginEndTime];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
        [BoxLoadingHelper showBoxWithMessage:error.localizedDescription];
    } withIsForm:YES];
    
    
    
}

-(void)getCaptchaCode{
    if (PMStringIsEmpty(self.phoneFiled.text)) {
        [BoxLoadingHelper showBoxWithMessage:ASLocalizedString(@"PhoneTips")];
        return;
    }
    if (![CurrentUser mine].isYNLanguage) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kRecordLoginStartTime];
        self.startTimeStr = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
        [[NSUserDefaults standardUserDefaults] setValue:self.startTimeStr forKey:kRecordLoginStartTime];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    [self startTimer];
}

- (void)startTimer{
    
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"translated":esString(self.phoneFiled.text),
        @"gari":@"gariCapture",
        @"adorning":@"adorningCapture"
    }.mutableCopy;
    
    [HttpNetHelper postNetworkHelperForPath:kCaptureUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        
        self.captureBtn.enabled = NO;
        if (!self.timer) {
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(upateTime) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }
        [self.timer fire];
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
    } withIsForm:YES];
    
    
    
}

- (void)upateTime{
    NSString * timeString = [NSString stringWithFormat:@"%ds", timeCount--];
    [self.captureBtn setTitle:timeString forState:UIControlStateDisabled];
    if (timeCount == 0) {
        [self stopTimer];
    }
}

- (void)stopTimer{
    if(self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    if(self.captureBtn){
        self.captureBtn.enabled = YES;
        [self.captureBtn setTitle:ASLocalizedString(@"Get") forState:UIControlStateNormal];
        timeCount = kDefaultTime;
    }
    
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */



@end
